package com.seashop.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author moredln
 * @desc
 * @date 2020-11-04 11:07
 */
@Configuration
public class RedisConfig {

    @Value(value = "${spring.redis.host}")
    private String redisHost;
    @Value(value = "${spring.redis.port}")
    private int redisPort;
    @Value(value = "${spring.redis.password}")
    private String password;

    @Bean(name = "redisTemplateZero") //0号库
    public RedisTemplate<String, Object> redisTemplateZero() {
        return getRedisTemplate(0);
    }

    @Bean(name = "redisTemplateOne") //1号库
    public RedisTemplate<String, Object> redisTemplateOne() {
        return getRedisTemplate(1);
    }

    @Bean(name = "redisTemplateTwo") //2号库
    public RedisTemplate<String, Object> redisTemplateTwo() {
        return getRedisTemplate(2);
    }

    @Bean(name = "redisTemplateThree") //3号库
    public RedisTemplate<String, Object> redisTemplateThree() {
        return getRedisTemplate(3);
    }

    @Bean(name = "redisTemplateFour") // 4号库
    public RedisTemplate<String, Object> redisTemplateFour() {
        return getRedisTemplate(4);
    }

    private RedisTemplate<String, Object> getRedisTemplate(int db) {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort);
        config.setDatabase(db);
        config.setPassword(password);
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(config);
        lettuceConnectionFactory.setValidateConnection(true);
        lettuceConnectionFactory.afterPropertiesSet();
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        // 设置 key 和 value 序列化模式
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        // 设置 hash key 和 value 序列化模式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        return redisTemplate;
    }

}
